import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/providers/providers.dart';
import 'package:merchants/providers/session_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyDefaultScreen extends ConsumerWidget {
  const MyDefaultScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的'),
        centerTitle: true,
        elevation: 2,
        backgroundColor: Theme.of(context).primaryColor.withValues(alpha: 0.95),
        automaticallyImplyLeading: false,
      ),
      body: SafeArea(
        bottom: false, // 不处理底部安全区域，让内容可以滚动
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 商品管理组
                _buildSectionHeader('商品管理', Icons.inventory),
                const SizedBox(height: 16),
                _buildManagementCard(
                  context,
                  icon: Icons.category,
                  title: '分类管理',
                  subtitle: '管理商品分类',
                  onTap: () => context.push('/tabs/category'),
                ),
                _buildManagementCard(
                  context,
                  icon: Icons.label,
                  title: '规格管理',
                  subtitle: '管理商品规格和规格值',
                  onTap: () => context.push('/tabs/attr-name'),
                ),
                
                const SizedBox(height: 24),
                
                // 系统管理组
                _buildSectionHeader('系统管理', Icons.settings),
                const SizedBox(height: 16),
                _buildManagementCard(
                  context,
                  icon: Icons.group,
                  title: '员工管理',
                  subtitle: '管理商户员工和权限',
                  onTap: () => context.push('/tabs/my/merchant-user-management'),
                ),
                _buildManagementCard(
                  context,
                  icon: Icons.security,
                  title: '角色管理',
                  subtitle: '管理系统角色和权限',
                  onTap: () => context.push('/tabs/my/role-management'),
                ),
                
                const SizedBox(height: 24),
                
                // 法律协议组
                _buildSectionHeader('法律协议', Icons.gavel),
                const SizedBox(height: 16),
                _buildManagementCard(
                  context,
                  icon: Icons.description,
                  title: '用户协议',
                  subtitle: '查看用户服务协议',
                  onTap: () => context.push('/tabs/my/agreement?type=user'),
                ),
                _buildManagementCard(
                  context,
                  icon: Icons.privacy_tip,
                  title: '隐私政策',
                  subtitle: '查看隐私保护政策',
                  onTap: () => context.push('/tabs/my/agreement?type=privacy'),
                ),
                
                const SizedBox(height: 24),
                
                // 账号管理组
                _buildSectionHeader('账号管理', Icons.account_circle),
                const SizedBox(height: 16),
                _buildManagementCard(
                  context,
                  icon: Icons.logout,
                  title: '退出登录',
                  subtitle: '切换账号或退出当前登录',
                  onTap: () => _showLogoutDialog(context, ref),
                  isDestructive: true,
                ),
                
                // 添加底部安全区域间距
                SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建分组标题
  Widget _buildSectionHeader(String title, IconData icon) {
    return Row(
      children: [
        Icon(
          icon,
          size: 20,
          color: Colors.grey[600],
        ),
        const SizedBox(width: 8),
        Text(
          title,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.grey[800],
          ),
        ),
      ],
    );
  }

  // 构建管理卡片
  Widget _buildManagementCard(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    bool isDestructive = false,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: ListTile(
        leading: Icon(
          icon,
          color: isDestructive ? Colors.red : Theme.of(context).primaryColor,
        ),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            color: isDestructive ? Colors.red : null,
          ),
        ),
        subtitle: Text(
          subtitle,
          style: TextStyle(
            color: isDestructive ? Colors.red.withOpacity(0.7) : Colors.grey[600],
          ),
        ),
        trailing: Icon(
          Icons.chevron_right,
          color: isDestructive ? Colors.red : Colors.grey[400],
        ),
        onTap: onTap,
      ),
    );
  }

  void _showLogoutDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('退出登录'),
          content: const Text('确定要退出当前账号吗？退出后需要重新登录。'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                await _logout(ref);
              },
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              child: const Text('退出'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _logout(WidgetRef ref) async {
    try {
      // 清除用户信息
      ref.read(authProvider.notifier).clear();
      
      // 清除会话信息
      await ref.read(sessionProvider.notifier).clear();
      
      // 清除本地存储（包括协议状态）
      final prefs = await SharedPreferences.getInstance();
      await prefs.clear();
      
      // 显示退出成功提示
      ScaffoldMessenger.of(ref.context).showSnackBar(
        const SnackBar(
          content: Text('已退出登录'),
          backgroundColor: Colors.green,
          duration: Duration(seconds: 2),
        ),
      );
      
      // 延迟跳转到登录页面
      Future.delayed(const Duration(milliseconds: 500), () {
        GoRouter.of(ref.context).pushReplacement('/login');
      });
    } catch (e) {
      ScaffoldMessenger.of(ref.context).showSnackBar(
        SnackBar(
          content: Text('退出失败：$e'),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }
}
